package org.feng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.feng.common.RequestHolder;
import org.feng.common.constant.CommonDictionaryConstant;
import org.feng.common.util.ExcelUtil;
import org.feng.common.util.StringUtil;
import org.feng.dto.request.AddUserRequestDto;
import org.feng.dto.request.UpdateUserRequestDto;
import org.feng.entity.CommonDictionary;
import org.feng.entity.User;
import org.feng.mapper.UserMapper;
import org.feng.sensitive.AbstractSensitive;
import org.feng.sensitive.Base64Sensitive;
import org.feng.service.ICommonDictionaryService;
import org.feng.service.IUserService;
import org.feng.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fengjinsong
 * @since 2023-08-24
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private ICommonDictionaryService commonDictionaryService;

    @Override
    public List<UserVO> listUser() {
        // 查询用户信息
        List<User> users = list();
        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }

        return users.stream()
                .map(user -> new UserVO().copyFieldByUser(user))
                .collect(Collectors.toList());
    }

    @Override
    public List<UserVO> listUserWithPermission() {
        // 查询用户信息
        List<User> users = this.getBaseMapper().listUserByCreateUserId();
        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }

        return users.stream()
                .map(user -> new UserVO().copyFieldByUser(user))
                .collect(Collectors.toList());
    }

    @Override
    public List<UserVO> listUserWithRolePermission() {
        // 查询用户信息
        List<User> users = this.getBaseMapper().listUserByRole();
        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }

        return users.stream()
                .map(user -> new UserVO().copyFieldByUser(user))
                .collect(Collectors.toList());
    }

    @Override
    public UserVO selectOneUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 名字精准匹配
        queryWrapper.lambda().eq(StringUtils.hasLength(username), User::getUsername, username);

        User user = this.getBaseMapper().selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            return null;
        }
        return new UserVO().copyFieldByUser(user);
    }

    @Override
    public Integer addUser(AddUserRequestDto addUserRequestDto) {
        User user = new User();
        user.setUsername(addUserRequestDto.getUsername());
        user.setAge(addUserRequestDto.getAge());
        user.setPhone(addUserRequestDto.getPhone());
        user.setEmail(addUserRequestDto.getEmail());

        int insertRows = this.getBaseMapper().insert(user);
        return insertRows <= 0 ? null : user.getId();
    }

    @Override
    public UserVO updateUser(UpdateUserRequestDto updateUserRequestDto) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(User::getId, updateUserRequestDto.getId());

        String username = updateUserRequestDto.getUsername();
        Integer age = updateUserRequestDto.getAge();
        String email = updateUserRequestDto.getEmail();
        String phone = updateUserRequestDto.getPhone();
        updateWrapper.lambda().set(StringUtils.hasLength(username), User::getUsername, username);
        updateWrapper.lambda().set(Objects.nonNull(age), User::getAge, age);
        updateWrapper.lambda().set(StringUtils.hasLength(email), User::getEmail, email);
        updateWrapper.lambda().set(StringUtils.hasLength(phone), User::getPhone, phone);

        User user = new User();
        user.setUsername(updateUserRequestDto.getUsername());
        user.setAge(updateUserRequestDto.getAge());
        user.setPhone(updateUserRequestDto.getPhone());
        user.setEmail(updateUserRequestDto.getEmail());
        user.setId(updateUserRequestDto.getId());
        this.getBaseMapper().update(user, updateWrapper);
        return new UserVO().copyFieldByUser(user);
    }

    @Override
    public void exportUser() throws IOException {
        // 查找字典配置：导出用户数据时需要排除的列
        CommonDictionary commonDictionary = commonDictionaryService.selectOneByCode(CommonDictionaryConstant.MP_USER_EXPORT_EXCLUDE_FIELDS);
        Set<String> excludeFieldsSet = Collections.emptySet();
        if (Objects.nonNull(commonDictionary)) {
            // 被排除的列
            String excludeFields = commonDictionary.getValue();
            excludeFieldsSet = StringUtil.splitToSet(excludeFields, StringUtil.ENGLISH_COMMA);
        }

        // 查询用户信息
        List<UserVO> users = this.listUser();
        if (CollectionUtils.isEmpty(users)) {
            log.info("用户数据为空");
        }

        for (UserVO user : users) {
            // 解密手机
            String phone = user.getPhone();
            if (StringUtils.hasLength(phone)) {
                user.setPhone(AbstractSensitive.getSensitiveByType(Base64Sensitive.SENSITIVE_TYPE_CODE).decrypt(user.getPhone()));
            }
        }

        // 导出文件名
        String filename = "用户数据" + System.currentTimeMillis();
        ExcelUtil.writeToWeb(users, filename, UserVO.class, filename, excludeFieldsSet, RequestHolder.RESPONSE_LOCAL.get());
    }

    @Override
    public List<Integer> listUserId(Integer userId) {
        return this.getBaseMapper().listUserId(userId);
    }
}
